package com.eshop.we.common;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


public class RespDateResponseWrapper extends HttpServletResponseWrapper implements RespDataResponse{

	private ByteArrayOutputStream _stream = new ByteArrayOutputStream();  
	
	private StringBuilder buffer = new StringBuilder();
	
	private HttpServletResponse response;
      
    public RespDateResponseWrapper(HttpServletResponse response) {  
        super(response); 
        this.response = response;
    }  
    /** 
     * 覆盖getWriter()方法，将字符流缓冲到本地 
     */  
    @Override  
    public PrintWriter getWriter() throws IOException {  
        return new RepPrintWriter(super.getWriter(),buffer);   
    }   
    /** 
     * 覆盖getOutputStream()方法，将字节流缓冲到本地 
     */  
    @Override  
    public ServletOutputStream getOutputStream() throws IOException {  
        return new ServletOutputStream(){
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {

            }

            @Override
            public void write(int b) throws IOException {  
                _stream.write(b);  
            }
            public void write(byte[] bytes) throws IOException {
            	_stream.reset();
                //将字节数组的内容写入缓存  
            	_stream.write(bytes);  
                //确保所有字节数组内容进入缓存  
            	_stream.flush();  
            }  
        };  
    }  
    /** 
     * 把缓冲区内容写入输出流后关闭 
     */  
    public void flush(){  
        try {  
            _stream.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    /** 
     * 获取字节流 
     * @return 
     */  
    public ByteArrayOutputStream getByteArrayOutputStream(){  
        return _stream;  
    }   
    /** 
     * 将换出区内容转为文本输出 
     * @return 
     */  
    public String getTextContent() {  
        flush(); 
        String rep;
		try {
			rep = new String(_stream.toByteArray(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			rep = null;
		}
        if(rep == null || rep.length() <= 0){
        	rep = buffer.toString();
        }
        return rep;  
    }
    
	@Override
	public HttpServletResponse getHttpServletResponse() {
		return response;
	}  
  
}  
